package com.summer_administration.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.summer_administration.mapper.IncomeMapper;
import com.summer_administration.pojo.Income;
import com.summer_administration.pojo.PageBean;
import com.summer_administration.service.IncomeService;
import com.summer_administration.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class IncomeServiceImpl implements IncomeService {
    @Autowired
    private IncomeMapper incomeMapper;

    @Override
    public void add(Income income) {
        //补充属性值
        income.setCreateTime(LocalDateTime.now());
        income.setUpdateTime(LocalDateTime.now());
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer)map.get("id");
        income.setCreateUser(userId);
        incomeMapper.add(income);
    }

    @Override
    public PageBean<Income> list(Integer pageNum, Integer pageSize,String method) {
        //1.创建PageBean对象
        PageBean<Income> pb = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum, pageSize);

        //3.调用mapper
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer)map.get("id");
        List<Income> as = incomeMapper.list(userId,method);
        //Page中提供了方法，可以获取PageHelper分类查询后 得到的总计条数和当前页数据
        Page<Income> p = (Page<Income>)as;

        //把数据填充到PageBean对象中
        //pb.setTotal(p.getTotal());
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    public void update(Income income) {
        income.setUpdateTime(LocalDateTime.now());
        incomeMapper.update(income);
    }

    @Override
    public void delete(Integer id) {
        incomeMapper.delete(id);
    }

    @Override
    public String getGroupIdByGroupName(String groupName) {
        return incomeMapper.findGroupIdByGroupName(groupName);
    }
}
